<?php

class LoginController extends Site_Controller_Action
{

    public function init()
    {   
        
    } 

    public function indexAction()
    {
        //if($this->_segmento->CTS_ID == 2){
            return $this->_helper->redirector('index', 'index', array());
        //}
    }
    
    public function loginajxAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        $this->_helper->viewRenderer->setRender('login');

        echo $retorn = $this->login();
    }
    
    public function login(){ 
        
        Zend_Loader::loadClass('auth','library');
        
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost();
            //Formulário corretamente preenchido?
            $login = $this->_getParam('l_usuario', 0);
            $senha = $this->_getParam('l_senha', 0);
                
            if (strlen($login) > 0 && strlen($senha) > 0) {
                
                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                //Inicia o adaptador Zend_Auth para banco de dados
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('USUARIOS')
                        ->setIdentityColumn('USU_LOGIN')
                        ->setCredentialColumn('USU_SENHA')
                        ->setCredentialTreatment('SHA1(?)');

                //Define os dados para processar o login
                $authAdapter->setIdentity($login)
                        ->setCredential($senha);
                
                //Efetua o login
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                
                //Verifica se o login foi efetuado com sucesso
                if($result->isValid()){ 
                    $info = $authAdapter->getResultRowObject(null, 'USU_SENHA');
                    $storage = $auth->getStorage();
                    $storage->write($info);
                    
                    // valida status do usuário
                    Zend_Loader::loadClass('usuario','library');
                    if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
                        //Dados inválidos
                        $this->_helper->FlashMessenger('Usuário ou senha inválidos!');
                        return $this->_helper->redirector('index', 'index', array());
                    }

                    Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());
                    
                    auth::montaSessao($auth,$authAdapter);
                    //$script = '<script>window.location.reload();</script>';
                    $script = '<script>window.location.href = "'.$this->_urlbase.'/'.$this->_modulo.'/";</script>';
                    $html = ''.$script;
                    
                    return json_encode(array('ok' => TRUE, 'html'=>$html)); 
                    
                }else{
                    return json_encode(array('ok' => FALSE, 'msg' => 'Usuário e/ou senha incorreto(s)!'));  
                }
            }
            else{
                return json_encode(array('ok' => FALSE, 'msg' => 'Usuário e/ou senha incorreto(s)!'));  
            }
        }    
        
    }
    
    public function loginAction() {
        
        $this->validaUserSessao();
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/login.js?1=2');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/cadastroescolar.js?1=1232');
        
        $emp_id = $this->_getParam('emp_id', 0);
        
        if($this->_segmento->CTS_ID == 2){
            
            if($emp_id <= 0) return $this->_helper->redirector('index', 'index', array());
            
            $this->view->dir_emp = 'public/upload/empresa/';
            $this->view->emp_id = $emp_id;
            $this->_helper->viewRenderer->setRender('cadastroescolar');
        }
        
        if($this->getRequest()->isPost()) {
            
            $retorn = json_decode($this->login(), true);
            
            if($retorn['ok'] == FALSE){
                echo '<script>alert("'.$retorn['msg'].'");</script>';
            }else{
                return $this->_helper->redirector('index', 'index', array());
            }
            
        }
        
    }
    
    public function logoutAction() {
        //Limpa dados da Sessão
        Zend_Auth::getInstance()->clearIdentity();

        return $this->_helper->redirector('index', 'index', array());
    }
    
    public function cadastroAction() {
        
        $this->validaUserSessao();
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/login.js');
        
        Zend_Loader::loadClass('auth','library');
        //$this->_helper->layout->disableLayout(); 
        //$this->_helper->viewRenderer->setNoRender(); 
        
        if($this->_segmento->CTS_ID == 2){
            return $this->_helper->redirector('cadastroescolar','login', array());
        }else{
            $this->_helper->viewRenderer->setRender('index');
        }
    }
    
    
    public function cadastroescolarAction() {
        
        $this->validaUserSessao();
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/jquery-ui-1.10.2.custom/css/custom-theme/jquery-ui-1.10.2.custom.css'); 
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/login.js?1=2');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/cadastroescolar.js?1=58');
        
        $this->view->dir_emp = 'public/upload/empresa/';
        $this->view->emp_id = $this->_getParam('emp_id', 0); 
        
        Zend_Loader::loadClass('auth','library');
        //$this->_helper->layout->disableLayout(); 
        //$this->_helper->viewRenderer->setNoRender(); 
    
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                
                //print_r($formData);
                
                $id = (int) $this->_getParam('USU_ID',0);
                
                $data = array(
                    //'USU_ID'        => $formData['USU_ID'],
                    'USU_EMAIL'     => $formData['email'],
                    'USU_LOGIN'     => $formData['usuario'],
                    'USU_CPF'       => $formData['cpf'],
                    'USU_NOME'      => $formData['nome'],
                    'PER_ID'        => 3 , // permissão usuários site
                    'USU_DATCAD'    => date('Y-m-d'),
                    'USU_TPO'       => 10, // 10 = escolar
                    'USU_SENHA'     => sha1($formData['senha']),
                    'USU_CADSTA'    => 1,
                    'USU_STA'       => 0,
                    'USU_END'       => $formData['endereco'],
                    'USU_TEL'       => $formData['telefone'],
                    'USU_NOMALU'    => $formData['aluno'],
                    'EMP_ID'        => $formData['emp_id'],
                );

                $obj = new Sistema_Model_DbTable_Usuarios();

                if ($id == 0){
                    $obj->insert($data);
                    $id =  $obj->getAdapter()->lastInsertId();
                }
                
                $this->sessaoUsuario($formData['usuario'],$formData['senha']);
                
                return $this->_helper->redirector('index', 'index', array());
                
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
            }
        }
    }
    
    public function sessaoUsuario($user,$senha) {
        
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        //Inicia o adaptador Zend_Auth para banco de dados
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
        $authAdapter->setTableName('USUARIOS')
                ->setIdentityColumn('USU_LOGIN')
                ->setCredentialColumn('USU_SENHA')
                ->setCredentialTreatment('SHA1(?)');

        //Define os dados para processar o login
        $authAdapter->setIdentity($user)
                ->setCredential($senha);

        //Efetua o login
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapter);

        $info = $authAdapter->getResultRowObject(null, 'USU_SENHA');
        $storage = $auth->getStorage();
        $storage->write($info);

        // valida status do usuário
        Zend_Loader::loadClass('usuario','library');
        if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
            //Dados inválidos
            $this->_helper->FlashMessenger('Usuário ou senha inválidos!');
            return $this->_helper->redirector('index', 'index', array());
        }

        Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());


        auth::montaSessao($auth,$authAdapter);
        
    }
    
    public function vercpfAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        $msg = '';
        
        $cpf = trim($this->_getParam('cpf', ''));
        
        $query = 'SELECT SQL_CACHE USU_CPF FROM USUARIOS WHERE USU_CPF like "'.$cpf.'"';
        $result = $this->db->fetchAll($query); 
        
        foreach($result as $res){
            if($res['USU_CPF'] == $cpf){ 
                $ok = TRUE;
                $msg = 'CPF já utilizado!';
            }
        }
         
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }
    
    public function veremailAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        $msg = '';
        
        $email = trim($this->_getParam('email', ''));
        
        $query = 'SELECT SQL_CACHE USU_EMAIL FROM USUARIOS WHERE USU_EMAIL like "'.$email.'"';
        $result = $this->db->fetchAll($query); 
        
        foreach($result as $res){
            if($res['USU_EMAIL'] == $email){ 
                $ok = TRUE;
                $msg = 'E-mail já utilizado!';
            }
        }
         
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }
    
    public function verusuarioAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        $msg = '';
        
        $usuario = trim($this->_getParam('usuario', ''));
        
        $query = 'SELECT SQL_CACHE USU_LOGIN FROM USUARIOS WHERE USU_LOGIN like "'.$usuario.'"';
        $result = $this->db->fetchAll($query); 
        
        foreach($result as $res){
            if($res['USU_LOGIN'] == $usuario){ 
                $ok = TRUE;
                $msg = 'Usuário já utilizado!';
            }
        }
         
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }
    
    public function validaUserSessao(){
        if(Zend_Auth::getInstance()->getStorage()->read()->USU_ID > 0){
            return $this->_helper->redirector('index', 'index', array());
        }
    }
}

